import { ElMessageBox, ElMessage } from "element-plus"

export const addUpdateFun = (form, addUpdate, addData, updateData, getData, dialogFormVisible) => {
  const onSubmit = (formEl) => {
    if (!formEl) return;
    // 提交按钮统一表单验证
    formEl.validate(async (valid) => {
      if (valid) {
        let data;
        if (addUpdate.value === "add") {
          // 添加
          data = await addData(form.value);
        } else {
          // 更新
          data = await updateData(form.value);
        }
        // 重新获取数据
        getData();
        ElMessage.success(data.msg);
        dialogFormVisible.value = false;
      } else {
        ElMessage.error("请正确填写表单信息!");
        return false;
      }
    });
  };
  return onSubmit
}

export const deleteFun = (name, deleteData, getData) => {
  const handleDelete = (index, row) => {
    ElMessageBox.confirm(`确定要删除${name}"${row.name}"吗?`, "友情提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const { msg } = await deleteData(row);
        // 重新获取数据
        getData();
        ElMessage.success(msg);
      })
      .catch(() => { });
  }
  return handleDelete
}